<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Di\Annotations;


use ReflectionNamedType;
use Selibra\Di\AnnotationConfigure;
use Selibra\Di\AnnotationExecEntity;
use Selibra\Di\Annotations\Protocol\SelibraAnnotationInterface;
use Selibra\Di\AutowiredFactory;
use Selibra\Di\DI;
use \Attribute;

/**
 * Class Autowired
 * @package selibra\annotations
 */
#[Attribute]
final class Autowired implements SelibraAnnotationInterface
{

    /**
     * 协程单例
     * @var string
     */
    const TYPE_SINGLE = 1;

    /**
     * 进程单例
     */
    const TYPE_PROCESS_SINGLE = 2;


    /**
     * @var string
     */
    protected string $autowiredType = '';

    /**
     * Autowired constructor.
     * @param string|null $autowiredType
     */
    public function __construct($autowiredType = null)
    {
        if (!empty($autowiredType)) {
            $this->autowiredType = $autowiredType;
        }
    }


    /**
     * @inheritDoc
     * @throws \Selibra\Di\Exception\NoImplementClass
     */
    public function exec(AnnotationExecEntity &$annotationExecEntity)
    {
        $execTime = $annotationExecEntity->getExecTime();
        $reflector = $annotationExecEntity->getProperty();
        if ($execTime === SelibraAnnotationConstants::EXEC_CALL && $reflector instanceof \ReflectionProperty) {

            // 调用的时候执行
            $type = $reflector->getType();
            if (!empty($type) && $type instanceof ReflectionNamedType) {
                $typeName = $type->getName();
                if ($this->autowiredType === self::TYPE_SINGLE) {
                    $context = AutowiredFactory::getInstantiation($typeName);
                } elseif ($this->autowiredType === self::TYPE_PROCESS_SINGLE) {
                    $context = AutowiredFactory::getInstantiation($typeName, false);
                } else {
                    $context = DI::getObjectContext($typeName);
                }
                $reflector->setValue($annotationExecEntity->getObject(), $context);
            }
        }
    }

    /**
     * @inheritDoc
     */
    public function configure(AnnotationConfigure $annotationConfigure)
    {
        // TODO: Implement configure() method.
    }
}